package main

import (
	"fmt"
	"runtime"
	"time"
)

func main() {
	// testGo()
	testGo2()
	// testGo3()
}

func testGo3() {
	var a [10]int
	for i := 0; i < 10; i++ {
		go func(ii int) {
			for {
				a[ii]++
				runtime.Gosched() // 主动交出控制权
			}
		}(i)
	}
	time.Sleep(time.Millisecond)
	fmt.Println(a)
}

func testGo2() {
	var a [10]int
	for i := 0; i < 10; i++ {
		go func(ii int) {
			for {
				a[ii]++
				// 主动交出控制权,否则会一直执行
				runtime.Gosched()
			}
		}(i)
	}
	time.Sleep(time.Millisecond)
	fmt.Println(a)
}

func testGo() {
	for i := 0; i < 1000; i++ {
		go func(i int) { // 匿名函数,把i 传进去,直接引用外面i不安全
			for {
				fmt.Printf("Hello from "+
					"goroutine %d\n", i)
			}
		}(i)
	}
	// time.Sleep(time.Minute)
	time.Sleep(time.Millisecond)
	// main如果推出 goroutine 也被杀掉
}
